package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"net/rpc"
	"net/url"
	"ultone/internal/log"
	"ultone/internal/opt"
	"ultone/internal/unix"
)

var (
	cliCommand = &cobra.Command{
		Use: "cli",
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			log.Debug(cmd.Context(), "[cmd.cli] svc address: %s", svc)

			uri, err := url.Parse(svc)
			if err != nil {
				return err
			}

			if cliClient, err = rpc.Dial(uri.Scheme, uri.Host+uri.Path); err != nil {
				return fmt.Errorf("rpc dial [%s] [%s] err: %w", uri.Scheme, uri.Host+uri.Path, err)
			}

			return nil
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			log.Debug(cmd.Context(), "[cli] start run cli... all args: %v", args)

			return nil
		},
	}

	svc       string
	cliClient *rpc.Client
)

func initCli() {
	cliCommand.PersistentFlags().StringVar(&svc, "svc", opt.RpcAddress, "server unix listen address")
	cliCommand.AddCommand(&cobra.Command{
		Use: "set",
		RunE: func(cmd *cobra.Command, args []string) (err error) {
			log.Debug(cmd.Context(), "[cli.set] all args: %v", args)

			if len(args) < 2 {
				return fmt.Errorf("at least 2 args required")
			}

			switch args[0] {
			case "debug":
				out := &unix.Resp[bool]{}
				in := &unix.SettingReq{Debug: false}
				switch args[1] {
				case "true":
					in.Debug = true
				case "false":
				default:
					return fmt.Errorf("unknown debug value")
				}

				if err = cliClient.Call("svc.Setting", in, out); err != nil {
					return err
				}

				log.Info(cmd.Context(), out.Msg)
			default:
				return fmt.Errorf("unknown set variable(debug is available now)")
			}

			return nil
		},
	})
}
